import { login, logout, getInfo, getNewToken } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken('szerp-loginToken'),
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, data) => {
    state.userInfo = data
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { loginAccount, loginPassWord } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: loginAccount.trim(), password: loginPassWord }).then(response => {
        console.log(response)
        setToken('authorization', response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        console.log(response)
        // const { data } = response
        // if (!data) {
        //   return reject('Verification failed, please Login again.')
        // }
        const { user } = response
        commit('SET_NAME', user.userName)
        // commit('SET_AVATAR', employeePicture)
        commit('SET_USERINFO', response)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
      // commit('SET_NAME', 'Super Admin')
      // commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
      // commit('SET_USERINFO', { employeeName: 'admin', employeeCode: 'Employee1', mobile: '18975555553' })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   commit('SET_ROLES', [])
      //   removeToken()
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
      commit('permission/SET_ROUTES', [], { root: true })
      commit('SET_TOKEN', '')
      resetRouter()
      removeToken('szerp-loginToken')
      removeToken('szerp-apiToken')
      removeToken('szerp-authorization')
      removeToken('authorization')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken('szerp-loginToken')
      removeToken('szerp-apiToken')
      removeToken('szerp-authorization')
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

